import {createVNode, render} from 'vue';
import Message from '@/components/Message.vue';

const messageTypes = ['success', 'warning', 'error', 'info'];

let messageQueue = [];
const GAP_SIZE = 16; // 消息之间的间距

const createMessage = (options) => {
    const container = document.createElement('div');
    const vm = createVNode(Message, {
        ...options,
        onDestroy: () => {
            render(null, container);
            container.remove();
            adjustMessagePositions();
            messageQueue = messageQueue.filter(item => item !== container);
        }
    });

    render(vm, container);
    document.body.appendChild(container);

    // 添加到队列并调整位置
    messageQueue.push(container);
    adjustMessagePositions();

    return vm.component;
};

const adjustMessagePositions = () => {
    const startTop = 20;
    messageQueue.forEach((container, index) => {
        const previousHeight = index > 0 ? messageQueue[index - 1].offsetHeight : 0;
        const top = startTop + index * (previousHeight + GAP_SIZE);
        container.style.top = `${top}px`;
    });
};

export const message = {
    ...messageTypes.reduce((acc, type) => {
        acc[type] = (message, duration = 3000) => createMessage({
            type,
            message,
            duration
        });
        return acc;
    }, {}),

    closeAll: () => {
        messageQueue.forEach(container => {
            render(null, container);
            container.remove();
        });
        messageQueue = [];
    }
};